<template>
  <div class="check">
    <!-- <audio id="myaudio" controls="controls" hidden src="../../../assets/mp3/wms称重成功.mp3" ref="audio"></audio> -->
    <div class="title">一单一品工位</div>
    <div class="checkTop">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="CODE">
          <el-input v-model="code" placeholder="CODE"></el-input>
        </el-form-item>
        <el-form-item style="display: none" label="CODE">
          <el-input v-model="code" placeholder="CODE"></el-input>
        </el-form-item>
      </el-form>
      <div class="checkSearch">
        <div class="h35">
             <span style="color: #F56C6C;margin-right: 4px;">*</span>
             <span class="wi50">波次号</span>
             <el-input v-model="waveId" size="mini" placeholder="波次号" clearable style="width: 200px;"></el-input>
        </div>
        <div class="h35">
              <span style="color: #F56C6C;margin-right: 4px;">*</span>
              <span class="wi50">code</span>
              <el-input v-model="code" size="mini" placeholder="code" clearable style="width: 200px;"></el-input>
        </div>
      </div>
    </div>
    <div class="checkBottom clearFloat">
      <div class="leftFloat">
        <transition name="el-zoom-in-center">
          <el-form
            v-show="billInfo.billNo != undefined"
            class="clearFloat"
            ref="form"
          >
            <el-form-item
              label="单号"
              prop="billNo"
              :label-width="formLabelWidth"
            >
              <span style="font-size: 20px; color: #000000">{{
                billInfo.billNo
              }}</span>
              <!-- <el-input  disabled v-model="billInfo.billNo"  placeholder=" " clearable style="width: 90%;"></el-input> -->
            </el-form-item>
            <el-form-item
              label="状态"
              prop="state"
              :label-width="formLabelWidth"
            >
              <el-tag v-if="billInfo.state == 6" type="success"
                >拣货完成</el-tag
              >
              <el-tag v-if="billInfo.state == 7" type="success"
                >成功复核</el-tag
              >
              <el-tag v-if="billInfo.state == 8" type="success"
                >成功发运</el-tag
              >
              <!-- <el-input  disabled v-model="billInfo.state"  placeholder=" " clearable style="width: 90%;"></el-input> -->
            </el-form-item>
            <el-form-item
              label="商品编码"
              prop="itemCode"
              :label-width="formLabelWidth"
            >
              <span style="font-size: 20px; color: #000000">{{
                billInfo.itemCode
              }}</span>
              <!-- <el-input disabled  v-model="billInfo.itemCode"  placeholder=" " clearable style="width: 90%;"></el-input> -->
            </el-form-item>
            <el-form-item
              label="商品名称"
              prop="itemName"
              :label-width="formLabelWidth"
            >
              <span style="font-size: 20px; color: #000000">{{
                billInfo.itemName
              }}</span>
              <!-- <el-input v-model="billInfo.itemName" placeholder="请输入物料名称" disabled clearable style="width: 90%;"></el-input> -->
            </el-form-item>
            <el-form-item
              label="图片"
              prop="batchId"
              :label-width="formLabelWidth"
            >
              <el-image
                style="width: 100px; height: 100px"
                :src="billInfo.imgUrl"
                :preview-src-list="[billInfo.imgUrl]"
              >
              </el-image>
            </el-form-item>
            <el-form-item label="预约数量" :label-width="formLabelWidth">
              <span
                v-if="billInfo.orderQuantity > billInfo.checkQuantity"
                style="font-size: 50px; color: #e6a23c"
                >{{ billInfo.orderQuantity }}</span
              >

              <span
                v-if="billInfo.orderQuantity == billInfo.checkQuantity"
                style="font-size: 50px; color: #67c23a"
                >{{ billInfo.orderQuantity }}</span
              >
              <el-progress
                :text-inside="true"
                :stroke-width="20"
                :percentage="
                  (billInfo.checkQuantity / billInfo.orderQuantity) * 100
                "
                status="success"
              ></el-progress>
            </el-form-item>

            <el-form-item label="扫描数量" :label-width="formLabelWidth">
              <el-input-number
                @change="checkQuantityChange"
                @focus="input0Set"
                :max="billInfo.orderQuantity"
                v-model="billInfo.checkQuantity"
                controls-position="right"
                :min="0"
                size="small"
                style="width: 90%"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="重量" :label-width="formLabelWidth">
              <span style="font-size: 50px; color: #67c23a">{{
                billInfo.weight
              }}</span>
            </el-form-item>
          </el-form>
        </transition>
      </div>
      <div class="rightFloat"></div>
    </div>

    <!-- <div class="createFootBox clearFloat" :style="{width: isCollapse ? 'calc(100% - 104px)' : 'calc(100% - 240px)'}">
      <div class="leftFloat">
        <el-button type="info" @click="$router.go(-1)">返 回</el-button>
      </div>
      <div class="rightFloat">
        <el-button @click="commitForm('form')" type="primary">确 认</el-button>
      </div>
    </div> -->
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "Check",
  data() {
    let validateQuantityNo0 = (rule, value, callback) => {
      if (value > 0) {
        callback();
      } else {
        callback(new Error("数量不得为0!"));
      }
    };
    return {
      code: "",
      wareId: PF.getLocal("wareId", "number"),
      itemCode: "",
      waveId: "",
      quantity: 0,
      billInfo: {
        checkQuantity: 1,
        orderQuantity: 1,
      },
      loading: {
        boxTable: false,
        pickTaskTable: false,
      },
      searchData: {
        pageNum: 1,
        pageSize: 5,
        total: null,
        wareId: PF.getLocal("wareId", "number"),
        state: 4,
        billNo: "SO-49",
      },
      searchData2: {
        pageNum: 1,
        pageSize: 5,
        total: null,
        wareId: PF.getLocal("wareId", "number"),
        boxNo: "",
      },

      formLabelWidth: "150px",

      pickTasks: [],
      boxDetails: [],
      packDetails: [],

      form: {
        soMasterId: null,
        soDetailId: null,
        billNo: "",
        boxNo: "",
        itemCode: "",
        itemName: "",
        batchs: "",
        batchId: "",
        batchName: "",
        quantity: 0,
        pickTaskId: null,
        pickQuantity: 0,
        packDetailId: null,
        packDescribe: "",
        memo: "",
      },
      rules: {
        itemCode: [
          { required: true, message: "请输入物料编码", trigger: "blur" },
        ],
        batchId: [{ required: true, message: "请选择批次", trigger: "blur" }],
        quantity: [
          { required: true, message: "请输入数量", trigger: "blur" },
          { validator: validateQuantityNo0, trigger: "blur" },
        ],
        packDetailId: [
          { required: true, message: "请选择单位", trigger: "blur" },
        ],
      },
    };
  },
  inject: ["home"],
  computed: {
    isCollapse() {
      return this.home.leftMenuIsCollapse;
    },
    isCheckBox() {
      return PF.isNull(this.form.boxNo);
    },
  },
  methods: {
    checkQuantityChange() {
      var that = this;
      if (that.billInfo.orderQuantity == that.billInfo.checkQuantity) {
        that.checkBill(that.billInfo.billNo);
      }
    },

    sendOut(billNo, wareId, weight) {
      IOT.getServerData(
        "/so/masters/sendOut",
        "get",
        {
          billNo: billNo,
          wareId: wareId,
          weight: weight,
        },
        (ret) => {
          this.loading.pickTaskTable = false;
          if (ret.code === 200) {
            this.billInfo.state = 8;
            this.$notify({
              title: "成功发运！",
              message: this.billInfo.billNo,
              type: "success",
            });
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        }
      );
    },
    printDzmd(billNo) {
      var that = this;
      IOT.getServerData(
        "/so/masters/getDzmd",
        "get",
        { billNo: billNo },
        (ret) => {
          if (ret.code === 200) {
            var strHTML = ret.data;
            that.$EventBus.$emit("printHtml", strHTML, null);
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        },
        true
      );
    },

    checkBill(billNo) {
      var that = this;
      IOT.getServerData(
        "/so/masters/check",
        "get",
        { billNo: billNo },
        (ret) => {
          if (ret.code === 200) {
            that.billInfo.state = 7;
            /**
             * 这里应该要打标签
             */
            //  var urlStr = 'http://lazerp2.oss-cn-hangzhou.aliyuncs.com/label/ztoth/77130044426681.pdf';
            //  that.$parent.printUrl(urlStr);
            that.printDzmd(billNo);
            this.$notify({
              title: "订单复核",
              message: that.billInfo.billNo,
              type: "success",
            });
          } else {
            IOT.tips(ret.message || "server error", "error");
          }
        }
      );
    },

    input0Set(e) {
      if (e.currentTarget.value == "0") {
        e.currentTarget.ariaValueNow = "";
        e.currentTarget.ariaValueText = "";
        e.currentTarget.value = "";
      }
    },
    getBillInfo() {
      var that = this;
      var param = {
        itemCode: that.itemCode,
        wareId: this.wareId,
      };
    },
    scanItemCode(itemCode) {
      var that = this;
      var billNo = that.billInfo.billNo;
      var state = that.billInfo.state;

      var list = itemCode.split(".");
      //如果拆分成两端则说明是称重数据，billInfo不为{}则有匹配到订单
      if (list.length == 2 && billNo != undefined) {
        if (that.billInfo.orderQuantity > that.billInfo.checkQuantity) {
          that.itemCode = "";
          this.$notify({
            title: "警告",
            message: "请扫描完该订单全部商品之后再进行称重！",
            type: "warning",
          });
        } else if (that.billInfo.state != 7) {
          that.itemCode = "";
          this.$notify({
            title: "警告",
            message: "该订单没有成功复核！",
            type: "warning",
          });
        } else if (
          (that.billInfo.orderQuantity = that.billInfo.checkQuantity)
        ) {
          that.billInfo.weight = itemCode;
          that.sendOut(that.billInfo.billNo, that.wareId, itemCode);
        }
      } else if (that.itemCode != itemCode || state == 8) {
        that.billInfo = {
          checkQuantity: 1,
          orderQuantity: 1,
        };
        that.itemCode = itemCode;
        var param = {
          itemCode: itemCode,
          wareId: this.wareId,
          waveId: this.waveId,
        };
        IOT.getServerData(
          "/so/masters/getYdypByItemCode",
          "get",
          param,
          (ret) => {
            if (ret.code === 200) {
              if (ret.data == null) {
                that.itemCode = "";
                that.$EventBus.$emit("playMusic", "wms未匹配到订单");
                this.$notify({
                  title: "警告",
                  message: "没有匹配到订单",
                  type: "warning",
                });
              } else {
                if (ret.data.state == 7) {
                  this.billInfo = ret.data;
                  ret.data.checkQuantity = orderQuantity;
                  that.billInfo.checkQuantity == that.billInfo.orderQuantity;
                } else {
                  ret.data.checkQuantity = 1;
                  ret.data.weight = "";
                  this.billInfo = ret.data;
                  this.$notify({
                    title: "匹配订单",
                    message: this.billInfo.billNo,
                    type: "success",
                  });
                  if (
                    that.billInfo.checkQuantity == that.billInfo.orderQuantity
                  ) {
                    this.billInfo.state = 7;
                    that.checkBill(that.billInfo.billNo);
                  }
                }
              }
            } else {
              IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
            }
          },
          true
        );
      } else if (
        that.itemCode == itemCode &&
        billNo != undefined &&
        list.length != 2
      ) {
        if (that.billInfo.checkQuantity == that.billInfo.orderQuantity) {
          that.itemCode = "";
          this.$notify({
            title: "警告",
            message: "该订单已复核！",
            type: "warning",
          });
        } else {
          that.billInfo.checkQuantity += 1;
          if (that.billInfo.checkQuantity == that.billInfo.orderQuantity) {
            that.checkBill(that.billInfo.billNo);
          }
        }
      }
    },

    getCode() {
      var that = this;
      var code = "";
      var lastTime, nextTime;
      var lastCode, nextCode;
      document.onkeypress = function (e) {
        nextCode = e.which;
        nextTime = new Date().getTime();
        var now = new Date().getTime();

        if (lastCode == null && lastTime == null) {
          if (e.key == "Enter") {
            //这里监听正常的键盘回车键
            that.scanItemCode(that.code);
            code = "";
            lastCode = null;
            lastTime = null;
          } else {
            code = e.key;
            lastCode = nextCode;
            lastTime = nextTime;
          }
        }
        //间隔大于500毫秒的是键盘输入的
        else if (
          lastCode != null &&
          lastTime != null &&
          nextTime - lastTime > 50
        ) {
          debugger;
          if (e.key == "Enter") {
            //这里监听正常的键盘回车键
            that.scanItemCode(that.code);
            code = "";
            lastCode = null;
            lastTime = null;
          } else {
            code = e.key;
            lastCode = nextCode;
            lastTime = nextTime;
          }
        }
        //间隔小于500毫秒的是扫码或者称重进来的
        else if (
          lastCode != null &&
          lastTime != null &&
          nextTime - lastTime <= 50
        ) {
          // 扫码枪
          if (e.key == "Enter") {
            that.scanItemCode(code);
            code = "";
            lastCode = null;
            lastTime = null;
          } else {
            code += e.key;
            lastCode = nextCode;
            lastTime = nextTime;
          }
        }
      };
    },

    getBillInfo() {},
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getPickTaskData();
    },
    handleCurrentChange2(val) {
      this.pageNum = val;
      this.getBoxDetailData();
    },
    clearSearchData() {
      this.searchData.billNo = "";
    },
    getPickTaskData() {
      let searchData = PF.JSON(this.searchData);
      if (!PF.isNull(searchData.billNo)) {
        IOT.tips("请输入单号！", "error");
        return false;
      }
      this.loading.pickTaskTable = true;
      IOT.getServerData("/pick/tasks/list", "get", searchData, (ret) => {
        this.loading.pickTaskTable = false;
        if (ret.code === 200) {
          this.pickTasks = ret.rows;
          this.searchData.total = ret.total;
          this.searchData.pageNum = ret.pageNumber;
        } else {
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },
    getBoxDetailData() {
      this.loading.boxTable = true;
      IOT.getServerData("/box/details/list", "get", this.searchData2, (ret) => {
        this.loading.boxTable = false;
        if (ret.code === 200) {
          this.boxDetails = ret.rows;
          this.searchData2.total = ret.total;
          this.searchData2.pageNum = ret.pageNumber;
        } else {
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },
    getPackDetailData(code) {
      IOT.getServerData(
        "/pack/details/list",
        "get",
        { packCode: code },
        (ret) => {
          if (ret.code === 200) {
            this.packDetails = ret.rows;
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        }
      );
    },
    getDetailItemData() {
      if (!PF.isNull(this.form.itemCode)) {
        return false;
      }
      let searchData = PF.JSON(this.searchData);
      if (!PF.isNull(searchData.billNo)) {
        IOT.tips("请输入单号！", "error");
        return false;
      }
      searchData.itemCode = this.form.itemCode;
      IOT.getServerData("/pick/tasks/list", "get", searchData, (ret) => {
        if (ret.code === 200) {
          if (ret.rows.length > 0) {
            let list = ret.rows[0];
            list.batchs = [];
            for (let i = 0; i < ret.rows.length; i++) {
              list.batchs.push({
                batchId: ret.rows[i].batchId,
                batchName: ret.rows[i].batchName,
              });
            }
            this.form.batchs = list.batchs;
            // this.form.inventoryId = list.inventoryId;
            this.form.soMasterId = list.soMasterId;
            this.form.soDetailId = list.soDetailId;
            this.form.itemCode = list.itemCode;
            this.form.itemName = list.itemName;
            this.form.batchId = list.batchId;
            this.form.batchName = list.batchName;
            this.form.packDetailId = list.packDetailId;
            this.form.packDescribe = list.packDescribe;
            this.form.pickTaskId = list.pickTaskId;
            this.form.pickQuantity = list.pickQuantity;
            this.getPackDetailData(list.packCode);
          } else {
            return false;
          }
        } else {
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },
    checkBoxNo() {
      this.form.boxNo = this.searchData2.boxNo;
    },
    clearBoxNo() {
      this.form.boxNo = "";
    },
    resetForm(formName) {
      // 重置
      this.$refs[formName].resetFields();
    },
    commitForm(formName) {
      let that = this;
      if (!PF.isNull(this.searchData.billNo)) {
        IOT.tips("请输入单号！", "error");
        return false;
      }
      if (!PF.isNull(this.form.boxNo)) {
        IOT.tips("未输入箱号,或箱号未锁定！", "error");
        return false;
      }
      IOT.showOverlay("保存中，请稍等...");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let form = PF.JSON(this.form);
          form.billNo = this.searchData.billNo;
          IOT.getServerData("/box/details/insert", "post", form, (ret) => {
            IOT.hideOverlay();
            if (ret.code === 200) {
              IOT.tips("保存成功！", "success", 1000, () => {
                that.getPickTaskData();
                that.getBoxDetailData();
              });
            } else {
              IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
            }
          });
          this.resetForm("form");
        } else {
          IOT.hideOverlay();
          console.error("error submit!!");
          return false;
        }
      });
    },
    changePackDetailId() {
      let form = PF.JSON(this.form);
      let packDetails = PF.JSON(this.packDetails);
      for (let i = 0; i < packDetails.length; i++) {
        if (packDetails[i].packDetailId === form.packDetailId) {
          this.form.packDescribe = packDetails[i].packDescribe;
        }
      }
    },
    isWithdraw(row) {
      this.$confirm("确认撤回？")
        .then((_) => {
          this.withdrawBoxDetail(row);
        })
        .catch((_) => {});
    },
    withdrawBoxDetail(row) {
      IOT.getServerData("/box/details/withdraw", "get", row, (ret) => {
        if (ret.code === 200) {
          IOT.tips("撤回成功！", "success");
        } else {
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },
  },
  created() {
    this.getCode();
  },
};
</script>

<style scoped lang="less">
.check {
  padding-bottom: 100px;
  .tableBox {
    padding-bottom: 0;
  }
  .checkSearch {
    border-bottom: 1px solid #dcdfe6;
    padding-bottom: 10px;
    > span {
      margin-right: 5px;
    }
  }
  .checkTop {
    margin-top: 5px;
    margin-right: 5px;
    border: 1px solid #dcdfe6;
    border-radius: 10px;
    padding: 10px 20px;
    background: #ffffff;
  }
  .checkBottom {
    margin-top: 10px;
    margin-right: 5px;
    > div {
      border: 1px solid #dcdfe6;
      border-radius: 10px;
      padding: 10px 20px;
      background: #ffffff;
    }
    .leftFloat {
      width: calc(55% - 47px);
    }
    .rightFloat {
      width: calc(45% - 47px);
    }
  }
}
</style>
